<template>
  <div>
    <a-card
      :bordered="false"
      :style="{marginTop: '20px'}"
      title="对应绩效">
      <div class="table-operator">
        <a-row :gutter="24">
          <a-col :md="3">
            <a-button
              type="primary"
              icon="plus"
              @click="createList">关联版本</a-button>
          </a-col>
          <a-col :md="7"><span>当前版本</span>
            <a-select
              style="width: 200px;margin-left: 15px"
              v-model="versionName"
              placeholder="请选择版本"
              :disabled="hasGrant">
              <a-select-option
                v-for="i in allVersion"
                :key="i"
                :value="i">
                {{ i }}
              </a-select-option>
            </a-select>
            <div
              style="display: inline;margin-left: 10px;"
              title="刷新"
              @click="refresh">
              <a-icon
                style="cursor: pointer"
                type="undo" />
            </div>
          </a-col>
          <a-col>
            <h3>{{ hasGrant ? `已有发放记录，无法切换版本，需要切换需要到提成记录页面撤销已发放金额` : '' }}
            </h3>
          </a-col>
        </a-row>
      </div>
      <div>
        <a-spin :spinning="loading">
          <s-table
            ref="table"
            size="default"
            :rowKey="'id'"
            :columns="columns"
            :data="loadData"
            :customRow="tableCustomRow"
            :showPagination="false">
            <span
              slot="job2"
              slot-scope="text">
              <template>
                <span>{{ labels.find(item => item.value === text) ? labels.find(item => item.value === text).label : '' }}</span>
              </template>
            </span>

            <span
              slot="evaluation"
              slot-scope="eva, record">
              <template>
                <!-- 1.级别2展示。2.如果有4列，项目经理绩效，展示。3.默认展示1。 -->
                <span>{{ record.level === 2 ? ([3,4,5,6,7,8].includes(record.job2) ? (eva ? `${eva.evaluation1}、${eva.evaluation2}、${eva.evaluation3}${eva.evaluation4 ? '、' + eva.evaluation4 : ''}` : '1' ): '无需参与评定'): '--' }}</span>
              </template>
            </span>

            <span
              slot="note"
              slot-scope="text">
              <ellipsis
                :length="20"
                tooltip>{{ text }}</ellipsis>
            </span>

            <span
              slot="action"
              slot-scope="text, record">
              <template>
                <a
                  v-if="record.evaluate"
                  style="margin-right: 8px"
                  @click="() => { showEvaModal(record) }">考核评定</a>
                <a
                  v-if="record.level === 2"
                  @click="() => { showUserModal(record) }">分配</a>
                <a
                  v-if="record.level === 3"
                  @click="() => { deletePer(record) }">删除</a>
              </template>
            </span>
          </s-table>
        </a-spin>
      </div>
      <create-form
        ref="createModal"
        :visible="visible"
        :isEdit="isEdit"
        :loading="confirmLoading"
        @cancel="handleCancel"
        @ok="handleOk" />
      <user-form
        ref="userModal"
        :visible="userVisible"
        :allUsers="teamUsers"
        @cancel="handleCancel"
        @ok="userOk" />
      <evaluate-form
        ref="evaluateModal"
        :visible="evaVisible"
        :rule="rule"
        :year="year"
        :version="version"
        @cancel="handleCancel"
        @ok="evaluateSubmit" />
    </a-card>
  </div>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import CreateForm from './CreateForm'
import EvaluateForm from './EvaluateForm'
import UserForm from './UserForm'
import {
  generaterformance,
  verifyPerformance,
  allocatePerformance,
  searchPerformance,
  evaluatePerformance,
  getRelatedVersions, // .查询已关联绩效参数年份版本
  deleteAllocate, // 绩效删除
  initialPerformance
} from '@/api/incentive'
import { columns } from './mock'
import { mapGetters } from 'vuex'
import { message } from 'ant-design-vue'

export default {
  name: 'Performance',
  props: {
    projectInfoProps: {
      type: Object,
      default: null
    },
    teamUsers: {
      type: Array,
      default: () => []
    }
  },
  components: {
    STable,
    CreateForm,
    EvaluateForm,
    Ellipsis,
    UserForm
  },
  data () {
    this.incomeExpensesColumns = []
    this.fileColumns = []
    this.columns = columns
    return {
      projectInfo: {},

      list: [],
      isAdd: false,
      isEdit: false,
      visible: false,
      loading: false,
      suppliers: undefined,
      confirmLoading: false,
      incomes: undefined,
      incomeRecord: undefined,
      income: undefined,
      year: undefined,
      version: undefined,
      // 已经发放，则选版本的下拉选disable
      hasGrant: false,
      versionName: undefined,
      // 已关联的所有版本
      allVersion: [],
      // allUsers: [],
      rule: {},
      // 考核表单
      evaVisible: false,
      // 分配表单
      userVisible: false,
      labels: [
        { label: '全职业务员提成', value: 1 },
        { label: '兼职业务员提成', value: 2 },
        { label: '项目经理提成', value: 3 },
        { label: '策划组提成', value: 4 },
        { label: 'UI设计&动效创意组提成 ', value: 5 },
        { label: '程序组提成 ', value: 6 },
        { label: '内容组(定制软件)提成', value: 7 },
        { label: '硬件开发组(定制硬件)提成', value: 8 },
        { label: '行政管理提成', value: 9 },
        { label: '项目组提成', value: 10 }
      ],
      // 附件
      files: undefined,
      fileTabLoading: false,
      fileCreateVisible: false,
      physicalSurveyCurrRowId: null,
      loadData: parameter => {
        if (!this.list.length) return Promise.resolve({ data: [], pagination: null })
        const defaultObj = { job2: '', name: '', fixedReward: '', grossReward: '', rate1: '', totalReward: '', rate: '', note: '' }
        const list = [{ ...defaultObj, type: '业务提成', level: 1, id: 0, job1: 1, children: [] },
        { ...defaultObj, type: '工程提成', job1: 2, level: 1, id: 1, children: [] },
        { ...defaultObj, type: '生产提成', job1: 3, level: 1, id: 2, children: [] },
        { ...defaultObj, type: '行政提成', job1: 4, level: 1, id: 3, children: [] }
        ]
        this.list.forEach((item, ind1) => {
          item.level = 2
          item.id = ind1 + 4
          if (item.children.length === 0) item.children = null
          // 业务提成 job2
          if (item.job2 === 1 || item.job2 === 2) {
            list[0].children.push(item)
          }
           // 工程提成 job2
          if (item.job2 === 3 || item.job2 === 10) {
            if (item.job2 === 3)item.evaluate = true
            list[1].children.push(item)
          }
          // 生产提成 job2
          if ([4, 5, 6, 7, 8].includes(item.job2)) {
            list[2].children.push(item)
            item.evaluate = true
          }
          if (item.job2 === 9) {
            list[3].children.push(item)
          }
          // 二级数据加上level
          if (item.children) {
            item.children.map((_sub, ind2) => {
              _sub.level = 3
              _sub.id = `${ind1}-${ind2}`
              // 三级数据加上level
              // if (_sub.children) {
              //   _sub.children.map((third, ind3) => {
              //     third.level = 3
              //     third.id = `${ind1}-${ind2}-${ind3}`
              //   })
              // }
            })
          }
        })
        return Promise.resolve({ data: list, pagination: null })
      }
    }
  },
  computed: {
    ...mapGetters(['menu'])
  },
  created () {},
  watch: {
    // userVisible: function (v) {
    //   if (this.allUsers.length < 1) {
    //     this.getUsers()
    //   }
    // },
    projectInfo: function (v) {
      if (v.projectId) {
        this.initPerformance({ projectId: v.projectId })
        getRelatedVersions({ projectId: v.projectId }).then(res => {
        this.hasGrant = res.data.some(item => item.flg === 'Y')
        this.allVersion = res.data.map(item => `${item.year}/${item.version}`)
      })
      }
    },
    versionName: function (v) {
      if (v !== `${this.year}/${this.version}`) {
        try {
          const [year, version] = v.split('/')
          this.initPerformance({ projectId: this.projectInfo.projectId, year, version })
        } catch (e) {}
      }
    }
  },
  mounted () {
    this.projectInfo = this.projectInfoProps
  },
  methods: {
    async deletePer (record) {
      const res = await deleteAllocate({ incentiveId: record.incentiveId })
      if (res.code === 0) {
        this.initPerformance()
      }
    },
    async initPerformance (param) {
      this.loading = true
      this._initPerformance(param).finally(() => {
        this.loading = false
      })
    },
    async _initPerformance (param) {
      if (param) {
        const listResp = await initialPerformance(param)
        // debugger
        if (listResp.data && listResp.data.length) {
          this.year = listResp.year
          this.version = listResp.version
          this.versionName = `${this.year}/${this.version}`
          // 拼接上分配比例
          const evas = await searchPerformance({
            year: this.year,
            version: this.version,
            projectId: param.projectId
          })
          this.loading = false
          this.list = listResp.data.map(item => {
            item.evaluation = evas.data[item.job2]
            return item
          })
          this.$refs.table.refresh()
        }
      } else {
        this._initPerformance({ projectId: this.projectInfo.projectId, year: this.year, version: this.version })
      }
    },
    createList () {
      this.visible = true
    },
    async refresh () {
      const projectId = this.projectInfo.projectId
      if (!projectId) return
      getRelatedVersions({ projectId }).then(res => {
        this.hasGrant = res.data.some(item => item.flg === 'Y')
        this.allVersion = res.data.map(item => `${item.year}/${item.version}`)
        this.initPerformance({ projectId })
      })
    },
    evaluateSubmit (param) {
      evaluatePerformance({
        projectId: this.projectInfo.projectId,
        year: this.year,
        version: this.version,
        job2: this.rule.job2,
        ...param
      }).then(() => {
        this.initPerformance({ projectId: this.projectInfo.projectId, version: this.version, year: this.year })
        this.handleCancel()
      })
    },
    async userOk (values) {
      const { incentiveName, performanceConfigId, job2 } = this.rule
      const totalRate = this.rule.children ? this.rule.children.reduce((pre, item) => {
        if (item.userId !== values.userId) return item.rate + pre
        else return pre
      }, 0) : 0
      if ((totalRate + values.rate) > 1) {
        return message.error('最大分配比例不能超过1')
      }
      const res = await allocatePerformance({
        incentiveName,
        performanceConfigId,
        job2,
        projectId: this.projectInfo.projectId,
        ...values
      })
      if (res.code === 0) {
        this.initPerformance()
        this.handleCancel()
      }
    },
    // getUsers () {
    //   allStaff().then(res => {
    //     this.allUsers = res.data
    //   })
    // },
    async handleOk (values) {
      const [year, version] = values.version
      this.year = year
      this.version = version

      const res = await verifyPerformance({ year, version })

      if (res.code !== 0) return
      await generaterformance({ year, version, projectId: this.projectInfo.projectId })
      this.refresh()
      // 拼接上分配比例
      // const evas = await searchPerformance({ year, version, projectId: this.projectInfo.projectId })

      // this.list = listResp.data.map(item => {
      //   item.evaluation = evas.data[item.job2]
      //   return item
      // })
      this.visible = false
      this.$refs.table.refresh()
    },
    showEvaModal (record) {
      this.evaVisible = true
      this.rule = record
    },
    showUserModal (record) {
      this.userVisible = true
      this.rule = record
    },
    handleCancel () {
      this.visible = false
      this.evaVisible = false
      this.userVisible = false
    },
    tableCustomRow (record, index) {
      return {
        style: {
          'background-color': record.level === 1 ? 'white' : record.level === 2 ? '#f0f0f0' : 'rgb(220, 220, 220)'
        },
        on: {
          click: event => {
            // this.physicalSurveyCurrRowId = record.id
            // this.conRecord = record
          }
        }
      }
    }
  }
}
</script>
